﻿using B.S.GridManage.Api.Read.Application.Command.UnitGrid;
using B.S.GridManage.Api.Read.Dtos;
using B.S.GridManage.Domain.Entities;
using B.S.GridManage.ErrorCode;
using B.S.GridManage.Infrastructure.Interface;
using MediatR;

namespace B.S.GridManage.Api.Read.Application.Handler.UnitGrid
{
    public class GetUnitGridHandler : IRequestHandler<GetUnitGridCommand, ApiPaging<UnitGridDto>>
    {
        private readonly IBaseRepository<UnitGirdModel> unitRepo;

        public GetUnitGridHandler(IBaseRepository<UnitGirdModel> unitRepo)
        {
            this.unitRepo = unitRepo;
        }

        /// <summary>
        /// 分页查询单元网格
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiPaging<UnitGridDto>> Handle(GetUnitGridCommand request, CancellationToken cancellationToken)
        {
            //实例化响应包装类
            ApiPaging<UnitGridDto> res = new ApiPaging<UnitGridDto>();

            //所有(单元)数据的表达式
            var units = unitRepo.GetAll().Where(x=>!x.IsDeleted);

            if (request.Id != null) {
                units = units.Where(x=>x.Id==request.Id);
            }


            var linq = from u in units
                       select new UnitGridDto { 
                          Id = u.Id,
                           UnitGridName = u.UnitGridName
                       };

            res.TotalCount = linq.Count();//总条数
            res.PageDatas  = linq.OrderByDescending(x => x.Id).Skip((request.PageIndex-1)*request.PageSize).Take(request.PageSize).ToList();
            res.Msg = "查询单元网格成功!";
            res.Code = ApiEnum.Success;
            return res;
        }
    }
}
